package com.naodong.shenluntiku.intergation.aliyunoss;

import android.os.Handler;
import android.os.Looper;

import com.alibaba.sdk.android.oss.ClientConfiguration;
import com.alibaba.sdk.android.oss.ClientException;
import com.alibaba.sdk.android.oss.OSSClient;
import com.alibaba.sdk.android.oss.ServiceException;
import com.alibaba.sdk.android.oss.callback.OSSCompletedCallback;
import com.alibaba.sdk.android.oss.callback.OSSProgressCallback;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationCredentialProvider;
import com.alibaba.sdk.android.oss.common.auth.OSSFederationToken;
import com.alibaba.sdk.android.oss.internal.OSSAsyncTask;
import com.alibaba.sdk.android.oss.model.PutObjectRequest;
import com.alibaba.sdk.android.oss.model.PutObjectResult;
import com.naodong.shenluntiku.app.BootstrapApplication;
import com.naodong.shenluntiku.mvp.model.bean.BaseBean;

import retrofit2.Call;
import retrofit2.Response;

/**
 * Created by hujie on 16/6/6
 * 阿里云oss管理.
 */
public class OssManager {


    private static final String BUCKET = "shenlun";
    private static final String ENDPOINT = "http://resources.newgs.net";

    private static OSSClient ossClient;


    private static OSSClient ossClient() {
        if (ossClient == null) {
            ossClient = new OSSClient(BootstrapApplication.getInstance().getApplicationContext(), ENDPOINT, createOSSFederationCredentialProvider(), createClientConfiguration());
        }
        return ossClient;
    }

    private static ClientConfiguration createClientConfiguration() {
        ClientConfiguration cof = new ClientConfiguration();
        cof.setConnectionTimeout(3 * 60 * 1000);
        cof.setSocketTimeout(5 * 60 * 1000);
        cof.setMaxErrorRetry(3);
        return cof;
    }

    /**
     * 创建一个oss权鉴提供者
     * 初始化OSSClient需要
     * @return
     */
    private static OSSFederationCredentialProvider createOSSFederationCredentialProvider() {
        OSSFederationCredentialProvider provider = new OSSFederationCredentialProvider() {
            @Override
            public OSSFederationToken getFederationToken() {
                try {
                    Call<BaseBean<StsToken>> call = BootstrapApplication.getInstance().getAppComponent().repositoryManager().obtainRetrofitService(StsTokenApi.class).getStsToken("ZqGYGTmcYrNJqDA3OtHiymMI2EY9vjYJNVIjdA6vkf4IWt");
                    Response<BaseBean<StsToken>> response = call.execute();
                    if (response.isSuccessful()) {
                        StsToken stsToken = response.body().getData();
                        OSSFederationToken token = new OSSFederationToken(stsToken.getAccessKeyId(), stsToken.getAccessKeySecret(), stsToken.getSecurityToken(), stsToken.getExpiration());
                        return token;
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }
                return null;
            }
        };

        return provider;
    }


    /**
     * 同步上传图片到oss
     * @param uploadFilePath
     * @return
     * @throws ClientException
     * @throws ServiceException
     */
    public static String putImage(String objectKey, String uploadFilePath) throws ClientException, ServiceException {
        PutObjectRequest request = new PutObjectRequest(BUCKET, objectKey, uploadFilePath);
        PutObjectResult result = ossClient().putObject(request);
        return objectKey;
    }

    /**
     * 异步上传图片到oss
     * @param uploadFilePath
     */
    public static OSSAsyncTask asyncPutImage(final String objectKey, String uploadFilePath, final OssUploadListener listener, final OSSProgressCallback ossProgressCallback) {

        PutObjectRequest request = new PutObjectRequest(BUCKET, objectKey, uploadFilePath);
        if (ossProgressCallback != null) {
            request.setProgressCallback(ossProgressCallback);
        }
        return ossClient().asyncPutObject(request, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                new Handler(Looper.getMainLooper()).post(() -> listener.onUploadSuccess(objectKey));
            }

            @Override
            public void onFailure(PutObjectRequest putObjectRequest, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常

                String errorMsg = null;
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();
                    errorMsg = "网络异常";
                }
                if (serviceException != null) {

                }
                final String finalErrorMsg = errorMsg;
                new Handler(Looper.getMainLooper()).post(() -> listener.onUploadFail(finalErrorMsg));

            }
        });
    }


    /**
     * 异步上传图片到oss
     * @param uploadFilePath
     */
    public static void asyncPutImage(final String objectKey, String uploadFilePath, final OssUploadListener listener) {

        PutObjectRequest request = new PutObjectRequest(BUCKET, objectKey, uploadFilePath);
        ossClient().asyncPutObject(request, new OSSCompletedCallback<PutObjectRequest, PutObjectResult>() {
            @Override
            public void onSuccess(PutObjectRequest putObjectRequest, PutObjectResult putObjectResult) {
                new Handler(Looper.getMainLooper()).post(() -> listener.onUploadSuccess(objectKey));
            }

            @Override
            public void onFailure(PutObjectRequest putObjectRequest, ClientException clientExcepion, ServiceException serviceException) {
                // 请求异常

                String errorMsg = null;
                if (clientExcepion != null) {
                    // 本地异常如网络异常等
                    clientExcepion.printStackTrace();

                }
                if (serviceException != null) {

                }
                final String finalErrorMsg = errorMsg;
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        listener.onUploadFail(finalErrorMsg);
                    }
                });

            }
        });
    }


}
